<template>
  <div class="container">
    <Breadcrumb :items="['menu.articleManage', 'menu.articleCate']" />
    <a-card class="custom-card" title="">
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button v-if="isExpandAll" type="primary" status="warning" @click="expandAll(isExpandAll)">
              <template #icon><icon-caret-down /></template>展开
            </a-button>
            <a-button v-else type="dashed" status="warning" @click="expandAll(isExpandAll)">
              <template #icon><icon-caret-up /></template>收缩
            </a-button>
            <a-button type="primary" @click="add()">
              <template #icon><icon-plus /></template>
              <template #default>添加</template>
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">

        </a-col>
      </a-row>
      <a-table
        ref="tableRef"
        row-key="id"
        :loading="loading"
        :pagination="false"
        :data="renderData"
        :bordered="{ wrapper: true, cell: true }"
        :row-selection="rowSelection"
        :scroll="tableScroll"
        column-resizable
        @selection-change="selectionChange"
      >
        <template #columns>
          <a-table-column title="名称" data-index="name" :width="160"/>
          <a-table-column title="描述" data-index="description" :tooltip="true" :width="200"/>
          <a-table-column title="排序" data-index="sorting" align="center" :width="100"/>
          <a-table-column title="是否显示" data-index="status" align="center" :width="80">
            <template #cell="{ record }">
              <a-switch v-model="record.status" :checked-value="1" :unchecked-value="2" @change="isActivate(record)"/>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="created_at" align="center" :width="180"/>
          <a-table-column title="操作" data-index="operations" align="center" fixed="right" :width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" size="small" @click="add(record)"><template #icon><icon-edit /></template>编辑</a-button>
                <a-button type="primary" status="danger" size="small" @click="del([record])"><template #icon><icon-delete /></template>删除</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <Detail
      ref="detailRef"
      :treeDatas="treeDatas"
      @saveCallback="fetchData"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, h, compile, getCurrentInstance } from 'vue';
  import { useI18n } from 'vue-i18n';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import screenHeight from '@/utils/screen-height';
  import { DataState, apiList, apiDel, apiDisable } from '@/api/category';
  import Detail from './components/detail.vue';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const height = screenHeight(216);
  const { proxy } = getCurrentInstance() as any;
  const renderData = ref<DataState[]>([]);
  const rowSelection = reactive({
    type: 'checkbox' as const,
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: height,
  });

  let selectionKeys: string[] = []; // 选中项ID
  const detailRef = ref();
  const isExpandAll = ref(true); // 展开/收缩

  const treeDatas = ref<DataState[]>([]);

  // 列表
  const fetchData = async () => {
    setLoading(true);
    try {
      const { data } = await apiList();
      renderData.value = data.data;
      treeDatas.value = data.data;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 添加/编辑
  const add = (row?: any) => {
    detailRef.value.fetchData(row);
  };
  // 删除
  const del = (row: any[]) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].name} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h(compile(message)),
        closable: true,
        hideCancel: false,
        onOk: (async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {
            setLoading(false);
          } finally {
            fetchData();
            setLoading(false);
          }
        }),
      });
    }
  };
  // 启用/禁用
  const isActivate = async (row: DataState) => {
    setLoading(true);
    await apiDisable({
      id: row.id,
      status: row.status
    });
    fetchData();
  };

  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys: any[]) => {
    selectionKeys = rowKeys;
  };
  const selectMsg = (message?: string) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys);
  };

  // 展开/收起
  const expandAll = (isExpand: boolean) => {
    isExpandAll.value = !isExpand;
    console.log(proxy);
    proxy?.$refs.tableRef.expandAll(isExpand);
  };

  fetchData();
</script>

<script lang="ts">
  export default {
    name: 'Category',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
